package com.h3c.nem.utils;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class I18nUtil {

    private static MessageSource messageSource;

    public I18nUtil(MessageSource messageSource) {
        I18nUtil.messageSource = messageSource;
    }

    public static String getMessage(String code) {
        return getMessage(code, null);
    }

    public static String getMessage(String code, Object[] args) {
        return getMessage(code, args, "");
    }

    public static String getMessage(String code, Object[] args, String defaultMessage) {
        Locale locale = LocaleContextHolder.getLocale();
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n/performance");
        String content;
        try {
            content = messageSource.getMessage(code, args, locale);
        } catch (Exception e) {
            System.out.println("获取提示消息失败： ->" + e);
            content = defaultMessage;
        }
        return content;
    }

    public static String getByLanguage(String msgKey, String defaultMsg, String language) {
        try {
            Locale locale = new Locale(language);   //中zh_CN  英en_US
            msgKey = messageSource.getMessage(msgKey, null, locale);
            return msgKey;
        } catch (Exception e) {
            return defaultMsg;
        }
    }

//    public static String getByLanguage(String msgKey) {
//        return getByLanguage(msgKey, null, "en_US");
//    }


}
